package leetcode_cn;

import nowcoder.offer.TreeNode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 三数之和
 *
 * @author briarbear
 * @blog https://briarbear.github.io
 * @date 2018-09-06 12:13
 */
public class ThreeSum {

    public List<List<Integer>> solution(int[] nums){
        //1. 对数组排序
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        int len = nums.length;

        for (int i = 0; i < len - 2; i++) {
            //2. 固定第一个元素，问题转化为求两个数之和
            if (i == 0 || nums[i-1] != nums[i]){  //3. 过掉选择了重复的元素
                int left = i + 1,right = len - 1,sum = 0 - nums[i];

                while (left < right){
                    if (nums[left] + nums[right] == sum){
                        res.add(Arrays.asList(nums[i],nums[left],nums[right]));
                        while (left < right && nums[left+1] == nums[left]) left++;  //4. 左侧游标移动，直到下一个不同的元素
                        left++;
                        while (left < right && nums[right-1] == nums[right]) right--;  //5. 右侧指针移动，直到下一个不同的元素
                        right--;
                    }else if (nums[left] + nums[right] > sum){
                        while (left < right && nums[right-1] == nums[right]) right--;
                        right--;
                    }else {
                        while (left < right && nums[left+1] == nums[left] ) left++;
                        left++;
                    }

                }

            }
        }
        return res;
    }

    public static void main(String[] args) {
        List<List<Integer>> res = new ThreeSum().solution(new int[]{0,0,0});

    }
}
